<template>
  <!-- 人均点击率 -->
  <div class="container">
    <el-row class="top-search">
      <el-col style="text-align: right;">
        <label for="">资讯类型</label>
        <el-select v-model="listQuery1.newsType" size="small" class="w-140">
          <el-option v-for="item in options5" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <label for="">资讯来源</label>
        <el-select v-model="listQuery1.sourceType" size="small" class="w-140">
          <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <label for="">语言</label>
        <el-select v-model="listQuery1.lang" size="small" class="w-140">
          <el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>

        <label for="">频道类型</label>
        <el-select v-model="listQuery1.channelType" size="small" class="w-140">
          <el-option v-for="item in options4" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>

        <date-range-picker
          v-model="datePicker1"
          type="daterange"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="timeChange"/>
        <el-button type="primary" icon="el-icon-search" size="small" @click="search1()">搜索</el-button>
      </el-col>
    </el-row>
    <el-row class="p-t-15">
      <el-col>
        <el-tabs ref="tabs" v-model="activeName" type="card">
          <el-tab-pane label="列表页推荐（人均阅读时长）" name="first">
            <div>
              <div class="echart">
                <div id="first" :style="{width: '100%', height: '480px'}"/>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <div class="dividing-line" style="margin:10px 0; border: 1px solid #e6e6e6"/>

    <el-row class="top-search">
      <el-col style="text-align: right;">
        <label for="">资讯类型</label>
        <el-select v-model="listQuery2.newsType" size="small" class="w-140">
          <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <label for="">资讯来源</label>
        <el-select v-model="listQuery2.sourceType" size="small" class="w-140">
          <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <label for="">语言</label>
        <el-select v-model="listQuery2.lang" size="small" class="w-140">
          <el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <date-range-picker
          v-model="datePicker2"
          type="daterange"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="timeChange"
        />
        <el-button type="primary" icon="el-icon-search" size="small" @click="search2()">搜索</el-button>
      </el-col>
    </el-row>
    <el-row class="p-t-15">
      <el-col>
        <el-tabs ref="tabs" v-model="activeName2" type="card">
          <el-tab-pane label="延展阅读（人均阅读时长）" name="two">
            <div>
              <div class="echart">
                <div id="two" :style="{width: '100%', height: '480px'}"/>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import echarts from 'echarts';
import { dateShortcutKeyJS } from '@/mixins/index.js';
import timeUtils from '@/utils/timeHandle.js';
import {
  newsReadTimeListApi,
  relationReadTimeListApi
} from '@/api/recommended-analysis.js';
export default {
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      options1: [{
        value: null,
        label: '全部'
      }, {
        value: 1,
        label: '图文'
      }, {
        value: 2,
        label: '图集'
      }, {
        value: 3,
        label: '视频'
      }, {
        value: 20,
        label: '专题'
      }],
      options2: [
        {
          value: null,
          label: '全部'
        },
        {
          value: 1,
          label: '爬虫'
        },
        {
          value: 2,
          label: '后台'
        },
        {
          value: 3,
          label: '自媒体'
        },
        {
          value: 4,
          label: '用户'
        }
      ],
      options3: [
        {
          value: null,
          label: '全部'
        },
        {
          value: 1,
          label: '中文'
        },
        {
          value: 2,
          label: '英/柬'
        }
      ],

      options4: [
        {
          value: null,
          label: '全部'
        },
        {
          value: 0,
          label: '推荐排序频道'
        },
        {
          value: 1,
          label: '时间排序频道'
        }
      ],
      options5: [{
        value: null,
        label: '全部'
      }, {
        value: 1,
        label: '图文'
      }, {
        value: 2,
        label: '图集'
      }, {
        value: 3,
        label: '视频'
      }, {
        value: 5,
        label: '微头条'
      },
      {
        value: 8,
        label: '小视频'
      },
      {
        value: 20,
        label: '专题'
      }],
      datePicker1: [timeUtils.timeHandle(
        new Date().getTime() - 3600 * 1000 * 24 * 7,
        'date'
      ),
      timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 1, 'date')],
      datePicker2: [timeUtils.timeHandle(
        new Date().getTime() - 3600 * 1000 * 24 * 7,
        'date'
      ),
      timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 1, 'date')],
      listQuery1: {
        beginTime: timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 7,
          'date'
        ),
        endTime: timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 1, 'date'),
        sourceType: null,
        newsType: null,
        lang: null,
        channelType: null
      },
      listQuery2: {
        beginTime: timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 7,
          'date'
        ),
        endTime: timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 1, 'date'),
        sourceType: null,
        newsType: null,
        lang: null
      },
      activeName: 'first',
      activeName2: 'two',
      xData1: [],
      xData2: [],
      listRatio: {},	// 列表阅读数据
      listClick: [] // 延展阅读数据
    };
  },
  mounted() {
    this.search1();
    this.search2();
  },
  methods: {
    // 获取指定时间段的每一天
    getDayAll(begin, end, noZeroFill) {
      // eslint-disable-next-line no-extend-native
      Date.prototype.format = function() {
        var s = '';
        s += this.getFullYear() + '-'; // 获取年份。
        if (noZeroFill) {
          s += (this.getMonth() + 1) + '-';
          s += this.getDate();
        } else {
          s += (this.getMonth() + 1) > 9 ? (this.getMonth() + 1) + '-' : '0' + (this.getMonth() + 1) + '-';
          s += this.getDate() > 9 ? this.getDate() : '0' + this.getDate();
        }
        return (s);
      };

      // eslint-disable-next-line no-array-constructor
      var dateAllArr = new Array();
      var ab = begin.split('-');
      var ae = end.split('-');
      var db = new Date();
      db.setUTCFullYear(ab[0], ab[1] - 1, ab[2]);
      var de = new Date();
      de.setUTCFullYear(ae[0], ae[1] - 1, ae[2]);
      var unixDb = db.getTime();
      var unixDe = de.getTime();
      for (var k = unixDb; k <= unixDe;) {
        dateAllArr.push((new Date(parseInt(k))).format().toString());
        k = k + 24 * 60 * 60 * 1000;
      }
      return dateAllArr;
    },
    timeChange(time) {

    },
    search1() {
      if (!this.datePicker1) {
        this.$message.warning('请输入搜索时间', true);
        return;
      }
      this.listQuery1.beginTime = this.datePicker1[0];
      this.listQuery1.endTime = this.datePicker1[1];

      // 选择小视频类型 只能选择全部频道类型
      if (this.listQuery1.newsType == 8) {
        this.listQuery1.channelType = null;
      }

      this.xData1 = this.getDayAll(this.listQuery1.beginTime, this.listQuery1.endTime);
      this.getData1();
    },
    search2() {
      if (!this.datePicker2) {
        this.$message.warning('请输入搜索时间', true);
        return;
      }
      this.listQuery2.beginTime = this.datePicker2[0];
      this.listQuery2.endTime = this.datePicker2[1];
      this.xData2 = this.getDayAll(this.listQuery2.beginTime, this.listQuery2.endTime);
      this.getData2();
    },

    getData1() {
      var myChart = echarts.init(document.getElementById('first'));
      myChart.showLoading();
      newsReadTimeListApi(this.listQuery1).then(res => {
        if (res.code == 200) {
          const getData = res.data;

          const nameMap = {
            'strategy_0': [],
            'strategy_-1': [],
            'strategy_3': [],
            'strategy_4': [],
            'strategy_6': [],
            'strategy_7': [],
            'strategy_8': [],
            'strategy_9': [],
            'strategy_10': [],
            'strategy_11': [],
            'strategy_501': [],
            'date': []
          };

          Object.keys(nameMap).forEach(key => {
            nameMap[key] = getData.map(item => {
              if (typeof item[key] === 'undefined') {
                return 0;
              } else if (key == 'date') {
                return item[key];
              } else {
                const num = Number(item[key]) == 0 ? 0 : Number(item[key]).toFixed(2);
                return num;
              }
            });
          });

          var Data = [];
          const xData = this.xData1;
          for (var i = 0; i < xData.length; i++) {
            var currentIndex = 0;
            const flag = nameMap.date.some(function(item, index) {
              currentIndex = index;
              return item == xData[i];
            });

            if (flag) {
              const obj = {
                'strategy_0': nameMap['strategy_0'][currentIndex],
                'strategy_-1': nameMap['strategy_-1'][currentIndex],
                'strategy_3': nameMap['strategy_3'][currentIndex],
                'strategy_4': nameMap['strategy_4'][currentIndex],
                'strategy_6': nameMap['strategy_6'][currentIndex],
                'strategy_7': nameMap['strategy_7'][currentIndex],
                'strategy_8': nameMap['strategy_8'][currentIndex],
                'strategy_9': nameMap['strategy_9'][currentIndex],
                'strategy_10': nameMap['strategy_10'][currentIndex],
                'strategy_11': nameMap['strategy_11'][currentIndex],
                'strategy_501': nameMap['strategy_501'][currentIndex],
                'date': nameMap['date'][currentIndex]
              };
              Data.push(obj);
            } else {
              const obj = {
                'strategy_0': 0,
                'strategy_-1': 0,
                'strategy_3': 0,
                'strategy_4': 0,
                'strategy_6': 0,
                'strategy_7': 0,
                'strategy_8': 0,
                'strategy_9': 0,
                'strategy_10': 0,
                'strategy_11': 0,
                'strategy_501': 0,
                'date': xData[i]
              };
              Data.push(obj);
            }
          }

          var list = {
            'strategy_0': [],
            'strategy_-1': [],
            'strategy_3': [],
            'strategy_4': [],
            'strategy_6': [],
            'strategy_7': [],
            'strategy_8': [],
            'strategy_9': [],
            'strategy_10': [],
            'strategy_11': [],
            'strategy_501': [],
            'date': []
          };

          for (var w = 0; w < Data.length; w++) {
            Object.keys(list).forEach(key => {
              list[key].push(Data[w][key]);
            });
          }

          this.listRatio = list;
          this.updateEchart1();
        } else {
          myChart.hideLoading();
        }
      }).catch(e => {
        myChart.hideLoading();
      });
    },
    updateEchart1() {
      var myChart = echarts.init(document.getElementById('first'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['全部策略', '其他', '最近阅读推荐', '热度推荐', '时效推荐', '长期标签', '短期标签', '搜索推荐', '动态推荐', '随机推荐', '专题'],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            type: 'category',
            data: this.listRatio['date']
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '(分钟)',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '全部策略',
            type: 'line',
            data: this.listRatio['strategy_0']
          },

          {
            name: '其他',
            type: 'line',
            data: this.listRatio['strategy_-1']
          },

          {
            name: '最近阅读推荐',
            type: 'line',
            data: this.listRatio['strategy_3']
          },

          {
            name: '热度推荐',
            type: 'line',
            data: this.listRatio['strategy_4']
          },

          {
            name: '时效推荐',
            type: 'line',
            data: this.listRatio['strategy_6']
          },

          {
            name: '长期标签',
            type: 'line',
            data: this.listRatio['strategy_7']
          },

          {
            name: '短期标签',
            type: 'line',
            data: this.listRatio['strategy_8']
          },

          {
            name: '搜索推荐',
            type: 'line',
            data: this.listRatio['strategy_9']
          },
          {
            name: '动态推荐',
            type: 'line',
            data: this.listRatio['strategy_10']
          },

          {
            name: '随机推荐',
            type: 'line',
            data: this.listRatio['strategy_11']
          },

          {
            name: '专题',
            type: 'line',
            data: this.listRatio['strategy_501']
          }
        ]
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
    },
    getData2() {
      var myChart = echarts.init(document.getElementById('two'));
      myChart.showLoading();
      relationReadTimeListApi(this.listQuery2).then(res => {
        if (res.code == 200) {
          const list = [];
          const arr = res.data || [];
          for (var i = 0; i < arr.length; i++) {
            list.push(arr[i].second || 0);
          }

          this.listClick = list;
          this.updateEchart2();
        } else {
          myChart.hideLoading();
        }
      }).catch(e => {
        myChart.hideLoading();
      });
    },
    updateEchart2() {
      var myChart = echarts.init(document.getElementById('two'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            type: 'category',
            data: this.xData2
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '(分钟)',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [{
          data: this.listClick,
          type: 'line'
        }]

      };

      myChart.setOption(option, true);
      myChart.hideLoading();
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
    margin: 15px;
    .w-140 {
        width: 140px;
    }
    .w-240 {
        width: 240px;
    }
    .title {
        height: 32px;
        position: relative;
        p {
            font-size: 22px;
            line-height: 32px;
            text-align: center;
        }
        .btn {
            width: 400px;
            height: 32px;
            position: absolute;
            right: 0;
            top: 0;
        }
    }
    .echart {
        width: 100%;
    }
    .search {
        text-align: right;
        padding: 15px;
        background-color: rgba(240, 242, 245, 1);
    }
    // 底部的echart
    .bottom-echart {
        .echart {
            position: relative;
            width: 45%;
            float: left;
            margin: 20px;
            .title {
                height: 32px;
                position: relative;
                p {
                    font-size: 22px;
                    line-height: 32px;
                    text-align: center;
                }
                .btn {
                    width: 400px;
                    height: 32px;
                    position: absolute;
                    right: 0;
                    top: 0;
                }
            }
            .num {
                position: absolute;
                right: 50px;
                bottom: 100px;
                li {
                    font-size: 14px;
                    line-height: 24px;
                    span {
                        padding: 0 10px;
                    }
                    .vertical {
                        padding: 0;
                        height: 24px;
                        width: 1px;
                        border: 1px solid #eee;
                    }
                }
            }
            .list {
                width: 508px;
                padding-top: 20px;
                float: right;
                li {
                    display: flex;
                    justify-content: space-between;

                    font-size: 22px;
                    line-height: 48px;
                    border-bottom: 1px solid #ccc;
                }
                .list-title {
                    font-size: 18px;
                    line-height: 56px;
                }
            }
        }
    }
}
</style>
